package com.wl.mvi.home

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.wl.lib.arouter.ARouterConstant
import com.wl.lib.arouter.service.IWebService
import com.wl.lib.mvi.BaseBindingVmFragment
import com.wl.lib.mvi.observeEvent
import com.wl.lib.mvi.observeState
import com.wl.lib.widget.LoadMoreFooterView
import com.wl.lib.widget.RecyclerAdapter
import com.wl.mvi.databinding.FragmentHomeBinding
import com.wl.mvi.home.model.bean.ArticleItem
import com.wl.mvi.home.model.bean.Banner
import com.wl.mvi.home.ui.ArticleItemView
import com.wl.mvi.home.ui.BannerItemView

// Created by wangliang on 2024/4/25.
class HomeFragment : BaseBindingVmFragment<FragmentHomeBinding, HomeViewModel>() {

    companion object {
        private const val TAG = "HomeFragment"
    }

    private val bannerAdapter: RecyclerAdapter by lazy {
        RecyclerAdapter().apply {
            val itemLayoutParams = {
                LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
            }
            registerViewType<BannerItemView, Banner>(itemLayoutParams) { itemView, item, _ ->
                itemView.render(item)
            }
        }
    }

    private val articleAdapter: RecyclerAdapter by lazy {
        RecyclerAdapter().apply {
            registerViewType<ArticleItemView, ArticleItem> { itemView, item, _ ->
                itemView.render(item)
            }
        }
    }

    private val loadMoreFooterView by lazy {
        LoadMoreFooterView(binding.recyView.context).apply {
            loadMore = { vm.sendUiIntent(HomeIntent.GetDetail) }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    private fun initView() {
        binding.viewPager.adapter = bannerAdapter

        binding.recyView.adapter = articleAdapter
        binding.recyView.layoutManager = LinearLayoutManager(context)
        binding.recyView.addItemDecoration(
            DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        )
        loadMoreFooterView.setup(binding.recyView)
    }


    private fun initData() {
        vm.sendUiIntent(HomeIntent.GetBanner)
        vm.sendUiIntent(HomeIntent.GetDetail)

        binding.testBtn.setOnClickListener {
            val webService = ARouter.getInstance().build(ARouterConstant.Web.SERVICE).navigation() as? IWebService
                ?: return@setOnClickListener
            context?.let { webService.showHtml(it, "file:///android_asset/test.html") }
            vm.sendUiIntent(HomeIntent.TestIntent)
        }

        binding.pageStateView.setReloadListener {
            vm.sendUiIntent(HomeIntent.GetBanner)
            vm.sendUiIntent(HomeIntent.GetDetail)
        }

        observeLoadUiState()
        observeBannerState()
        observeDetailState()

        observeEvent()
    }

    private fun observeLoadUiState() {
        vm.loadUiState.observeState(lifecycleScope) {
            binding.pageStateView.render(it, vm.firstLoadFinished) {
                // 显示主界面
                binding.viewPager.isVisible = true
            }
        }
    }

    private fun observeEvent() {
        vm.uiEvent.observeEvent(lifecycleScope) {
            when (it) {
                is HomeEvent.TestEvent -> {
                    Toast.makeText(context, it.msg, Toast.LENGTH_SHORT).show()
                }

                is HomeEvent.DetailNetError -> {
                    loadMoreFooterView.loadMoreState = LoadMoreFooterView.LoadMoreState.LOAD_ERROR
                }
            }
        }
    }

    private fun observeBannerState() {
        vm.bannerState.observeState(lifecycleScope) { bannerUiState ->
            // render banner
            Log.d(TAG, "bannerUiState: $bannerUiState")

            binding.viewPager.isVisible = true
            bannerAdapter.data.clear()
            bannerAdapter.data.addAll(bannerUiState.banners)
            bannerAdapter.notifyDataSetChanged()
        }
    }

    private fun observeDetailState() {
        vm.detailState.observeState(lifecycleScope) { detailUiState ->
            // render detail
            Log.d(
                TAG,
                "detailUiState: $detailUiState curPage: ${detailUiState.article?.curPage} size: ${detailUiState.article?.datas?.size}"
            )

            binding.recyView.isVisible = true

            if (detailUiState.article?.curPage == 1) {
                articleAdapter.data.clear()
            }
            val list = detailUiState.article?.datas ?: arrayListOf()
            if (list.isNotEmpty()) {
                if (!articleAdapter.containFooterView(loadMoreFooterView)) {
                    articleAdapter.addFooterView(loadMoreFooterView.apply {
                        loadMoreState = LoadMoreFooterView.LoadMoreState.NORMAL
                        isBound = true
                    })
                }

                loadMoreFooterView.hasMore = true

                articleAdapter.data.addAll(list)
                articleAdapter.notifyDataSetChanged()
            } else {
                loadMoreFooterView.hasMore = false
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("WLTest", "HomeFragment onCreateView")
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onStart() {
        Log.d("WLTest", "HomeFragment onStart")
        super.onStart()
    }

    override fun onResume() {
        Log.d("WLTest", "HomeFragment onResume")
        super.onResume()
    }

    override fun onPause() {
        Log.d("WLTest", "HomeFragment onPause")
        super.onPause()
    }

    override fun onStop() {
        Log.d("WLTest", "HomeFragment onStop")
        super.onStop()
    }

    override fun onDestroyView() {
        Log.d("WLTest", "HomeFragment onDestroyView")
        super.onDestroyView()
    }

}
